/*
 * @Author: Zhengxuan Ye
 * @Date: 2025-05-06 22:30:00
 * @Last Modified by: Zhengxuan Ye
 * @Last Modified time: 2025-05-06 22:30:00
 */

<template>
  <div class="social-interaction">
    <div class="interaction-header">
      <h2 class="section-title">互动交流</h2>
      <p v-if="!isLoggedIn" class="login-tip">
        <router-link to="/login">登录</router-link>后可参与点赞、评论和分享
      </p>
    </div>

    <div class="interaction-buttons">
      <button
        @click="handleLike"
        :class="['interaction-btn', 'like-btn', { active: likeStatus.liked }]"
        :disabled="!isLoggedIn"
      >
        <span class="icon">👍</span>
        <span class="label">{{ likeStatus.liked ? '已点赞' : '点赞' }}</span>
        <span class="count">{{ likeStatus.count }}</span>
      </button>

      <button
        @click="handleShare"
        class="interaction-btn share-btn"
        :disabled="!isLoggedIn"
      >
        <span class="icon">🔗</span>
        <span class="label">分享</span>
        <span class="count">{{ sharesCount }}</span>
      </button>
    </div>

    <!-- 评论区域 -->
    <div class="comments-section">
      <h3>评论 ({{ comments.length }})</h3>

      <!-- 评论输入框 -->
      <div class="comment-form">
        <textarea 
          v-model="commentContent" 
          :placeholder="isLoggedIn ? '写下您的评论...' : '请登录后评论...'" 
          rows="3" 
          :disabled="!isLoggedIn || commentLoading"
        ></textarea>
        <button 
          @click="submitComment" 
          class="submit-comment-btn" 
          :disabled="!isLoggedIn || !commentContent.trim() || commentLoading"
        >
          {{ commentLoading ? '提交中...' : '提交评论' }}
        </button>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list" v-if="comments.length > 0">
        <div class="comment-items">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <strong class="comment-author">{{ comment.username }}</strong>
              <span class="comment-time">{{ formatDate(comment.created_at) }}</span>
            </div>
            <div class="comment-body">
              {{ comment.content }}
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-comments">
        暂无评论，快来发表您的看法吧！
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useInteractionStore } from '../stores/interaction'

export default {
  name: 'SocialInteraction',
  props: {
    pageId: {
      type: [Number, String],
      required: true
    },
    pageType: {
      type: String,
      default: 'featured'
    }
  },
  setup(props) {
    const router = useRouter()
    const userStore = useUserStore()
    const interactionStore = useInteractionStore()
    
    const isLoggedIn = computed(() => userStore.isLoggedIn)
    const token = computed(() => userStore.token)
    
    const comments = ref([])
    const likeStatus = ref({ liked: false, count: 0 })
    const sharesCount = ref(0)
    const commentContent = ref('')
    const commentLoading = ref(false)

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    }

    // 加载评论
    const loadComments = async () => {
      try {
        const numericId = parseInt(props.pageId)
        console.log(`加载评论，页面ID: ${numericId}，类型: ${props.pageType}`)
        
        const result = await interactionStore.getComments(numericId)
        console.log('获取到的评论:', result)
        comments.value = result || []
      } catch (error) {
        console.error('加载评论失败:', error)
      }
    }

    // 检查点赞状态
    const checkLikeStatus = async () => {
      try {
        const numericId = parseInt(props.pageId)
        console.log(`检查点赞状态，页面ID: ${numericId}，类型: ${props.pageType}`)
        
        const status = await interactionStore.checkLikeStatus(numericId, token.value)
        console.log('点赞状态:', status)
        likeStatus.value = status || { liked: false, count: 0 }
      } catch (error) {
        console.error('检查点赞状态失败:', error)
        likeStatus.value = { liked: false, count: 0 }
      }
    }

    // 加载分享数
    const loadSharesCount = async () => {
      try {
        const numericId = parseInt(props.pageId)
        console.log(`加载分享数，页面ID: ${numericId}，类型: ${props.pageType}`)
        
        const count = await interactionStore.getSharesCount(numericId)
        console.log('获取到的分享数:', count)
        sharesCount.value = count || 0
      } catch (error) {
        console.error('加载分享数失败:', error)
        sharesCount.value = 0
      }
    }

    // 处理点赞
    const handleLike = async () => {
      if (!isLoggedIn.value) {
        router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
        return
      }

      try {
        const numericId = parseInt(props.pageId)
        console.log(`发送点赞请求，页面ID: ${numericId}，类型: ${props.pageType}`)
        
        const status = await interactionStore.toggleLike(numericId, token.value)
        console.log('点赞响应:', status)
        if (status) {
          likeStatus.value = status
        }
      } catch (error) {
        console.error('点赞操作失败:', error)
      }
    }

    // 处理分享
    const handleShare = async () => {
      if (!isLoggedIn.value) {
        router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
        return
      }

      try {
        const numericId = parseInt(props.pageId)
        
        // 复制链接到剪贴板
        const url = window.location.href
        await navigator.clipboard.writeText(url)
        console.log('链接已复制到剪贴板:', url)
        
        // 记录分享
        console.log(`发送分享请求，页面ID: ${numericId}，类型: ${props.pageType}`)
        const count = await interactionStore.sharePage(numericId, token.value)
        console.log('分享响应:', count)
        if (count !== null) {
          sharesCount.value = count
        }
        
        alert('链接已复制到剪贴板，可以分享给朋友了')
      } catch (error) {
        console.error('分享失败:', error)
        alert('分享失败，请手动复制链接')
      }
    }

    // 提交评论
    const submitComment = async () => {
      if (!isLoggedIn.value) {
        router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
        return
      }

      if (!commentContent.value.trim()) return

      commentLoading.value = true
      try {
        const numericId = parseInt(props.pageId)
        console.log(`发送评论请求，页面ID: ${numericId}，类型: ${props.pageType}，评论内容: ${commentContent.value}`)
        
        const result = await interactionStore.addComment(
          numericId,
          commentContent.value,
          token.value
        )
        console.log('评论响应:', result)
        
        // 清空评论内容
        commentContent.value = ''
        
        // 重新加载评论
        await loadComments()
      } catch (error) {
        console.error('提交评论失败:', error)
      } finally {
        commentLoading.value = false
      }
    }

    // 组件挂载时加载数据
    onMounted(async () => {
      await Promise.all([
        loadComments(),
        checkLikeStatus(),
        loadSharesCount()
      ])
    })

    return {
      isLoggedIn,
      comments,
      likeStatus,
      sharesCount,
      commentContent,
      commentLoading,
      handleLike,
      handleShare,
      submitComment,
      formatDate
    }
  }
}
</script>

<style scoped>
/* 社交互动部分样式 */
.social-interaction {
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid #e0e0e0;
}

.interaction-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-tip {
  font-size: 0.9rem;
  color: #666;
}

.login-tip a {
  color: var(--primary-color);
  text-decoration: none;
}

.interaction-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.interaction-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: var(--border-radius);
  background-color: white;
  cursor: pointer;
  transition: var(--transition);
}

.interaction-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.interaction-btn:not(:disabled):hover {
  border-color: var(--primary-color);
}

.like-btn.active {
  background-color: rgba(184, 134, 11, 0.1);
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.icon {
  font-size: 1.2rem;
}

.count {
  font-size: 0.9rem;
  color: #666;
  margin-left: 5px;
}

/* 评论区域样式 */
.comments-section {
  margin-top: 30px;
}

.comments-section h3 {
  font-size: 1.3rem;
  margin-bottom: 20px;
  color: var(--dark-color);
}

.comment-form {
  margin-bottom: 30px;
}

.comment-form textarea {
  width: 100%;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: var(--border-radius);
  resize: vertical;
  font-family: inherit;
  font-size: 1rem;
  margin-bottom: 15px;
}

.comment-form textarea:focus {
  outline: none;
  border-color: var(--primary-color);
}

.submit-comment-btn {
  padding: 10px 20px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: var(--transition);
}

.submit-comment-btn:hover:not(:disabled) {
  background-color: var(--accent-color);
}

.submit-comment-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 20px;
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  margin-bottom: 15px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.comment-author {
  color: var(--dark-color);
}

.comment-time {
  font-size: 0.85rem;
  color: #888;
}

.comment-body {
  line-height: 1.6;
  color: #333;
}

.no-comments {
  text-align: center;
  padding: 30px;
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  color: #666;
}
</style>
